#$gender_file="TCGA_SNP_Aliquot_Gender_Info.txt";
#reading the Clinical file
$gender_file=$ARGV[0];
chomp($gender_file);
open(BUFF,"$gender_file") or die "no file found $gender_file\n";
$line=<BUFF>;
chomp($line);
@split=split("\t",$line);
for($i=0;$i<@split;$i++)
{
	if($split[$i] eq "Subject ID")
	{
		$aliquot_num=$i;
	}
	if($split[$i] eq "Gender")
        {
                $gender_num=$i;
        }
}
#creating hash map of sample id and gender
print "Aliquot Column : $aliquot_num Gender : $gender_num\n";
while(<BUFF>)
{
	chomp($_);
	@array = split("\t",$_);
	$aliquot=$array[$aliquot_num];
	$gender=$array[$gender_num];
	if($aliquot =~ /\w/ && $gender =~ /\w/)
	{
		$gender{$aliquot}=$gender;
	}
}
$infile=$ARGV[1];
$outfile=$ARGV[2];
$sample_remove = $ARGV[3];
chomp($sample_remove);
chomp($infile);
chomp($outfile);
#opening the tfam file
open(INFILE,$infile) or die "no file $infile\n";
#opening to write the tfam file
open(OUTFILE,">$outfile") or die "can't write file $outfile\n";
#samplss to be remove as no gender code is available
open(OUTFILE1,">$sample_remove")  or die "can't write file $outfile1\n";
#Reading the file
while(<INFILE>)
{
	chomp($_);
	@tfam=split(" ",$_);
	@subject = split('-',$tfam[1]);
	$subject="$subject[0]-$subject[1]-$subject[2]";
	#print $subject."\n";
	if($tfam[4] < 1 || $tfam[4] > 2)
	{
		if(exists($gender{$subject}))
		{
			if($gender{$subject} eq "Female")
			{	
				$tfam[4] =2;
			}
			elsif($gender{$subject} eq "Male")
			{
				$tfam[4] =1;
			}
			else
			{
				die "gender code found but not valid$_\n";
			}
		}	
		else
		{
			#print "Error indicator : no gender code found $_\n";
			print OUTFILE1 $_."\n";
		}
		$_ = join(" ",@tfam);
	}
	print OUTFILE $_."\n";
}	
